<template>
  <div class="top-container">
    <!-- 标题栏 -->
    <div class="top-header">
      <!-- 左侧时间显示 -->
      <div class="time-display">
        <span class="date-number">{{ currentYear }}</span>
        <span class=date-text>年</span>
        <span class="date-number">{{ currentMonth }}</span>
        <span class=date-text>月</span>
        <span class="date-number">{{ currentDay }}</span>
        <span class=date-text>日</span>
        <span class="weekday">{{ currentWeekday }}</span>
        <span class="time">{{ currentTime }}</span>
      </div>
      
      <!-- 中间标题 -->
      <p>重庆高速隧道群控平台</p>
      
      <!-- 右侧预留空间，保持布局平衡 -->
      <div class="header-right"></div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <div class="search-input-container">
        <input
          type="text"
          placeholder="请输入路段名称"
          class="search-input search-left"
        />
        <div class="search-icon">
          <i class="fas fa-search"></i>
        </div>
      </div>
      <div class="search-input-container">
        <input
          type="text"
          placeholder="请选择隧道"
          class="search-input search-right"
        />
        <div class="search-icon">
          <i class="fas fa-chevron-down"></i>
        </div>
      </div>
    </div>

    <!-- 导航栏  -->
    <div class="nav-bar">
      <div
        class="nav-item"
        v-for="(item, index) in navList"
        :key="item"
        :class="{ active: activeNavIndex === index }"
        @click="onNavClick(item, index)"
      >
        <div class="icon-indicator" v-if="activeNavIndex === index"></div>
        <div class="nav-text">{{ item }}</div>
      </div>
    </div>

    <!-- 左下角模式切换按钮 -->
    <div class="mode-buttons">
      <div
        v-for="(mode, index) in modeList"
        :key="mode"
        class="mode-button"
        :class="{ active: activeModes[index] }"
        @click="onModeClick(mode, index)"
      >
        {{ mode }}
      </div>
    </div>

    <!-- 底部中间控制按钮 -->
    <div class="bottom-buttons">
      <div class="bottom-btn-bg" :class="{active: bottomBtnActiveIndex === 0}">
        <button class="bottom-btn tunnel-camera" :class="{ active: bottomBtnActiveIndex === 0 }" @click="onBottomBtnClick(0)">
          <span>隧道摄像机</span>
        </button>
      </div>
      <div class="bottom-btn-bg" :class="{active: bottomBtnActiveIndex === 1}">
        <button class="bottom-btn tunnel-event" :class="{ active: bottomBtnActiveIndex === 1 }" @click="onBottomBtnClick(1)">
          <span>隧道突发事件</span>
        </button>
      </div>
    </div>

    <!-- 右下角缩放控制按钮 -->
    <div class="zoom-controls">
      <button class="zoom-btn zoom-in">
        <img src="@/assets/image/TunnelOverviewPanel/组 50 拷贝 2.png" width="48" height="48" alt="放大" />
      </button>
      <button class="zoom-btn zoom-out">
        <img src="@/assets/image/TunnelOverviewPanel/组 50 拷贝 3.png" width="48" height="48" alt="缩小" />
      </button>
    </div>

    <!-- 右侧内容面板 - 使用动态组件 -->
    <div class="right-panel" v-if="activeNavIndex >= 2">
      <component :is="currentPanelComponent"></component>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeMount, watch, inject, getCurrentInstance } from "vue";
import { useRouter, useRoute } from 'vue-router';
import PanelContainer from './panels/PanelContainer.vue';
import TunnelOverviewPanel from './panels/TunnelOverviewPanel.vue';
import GuardPointsPanel from './panels/GuardPointsPanel.vue';
import DeviceOverviewPanel from './panels/DeviceOverviewPanel.vue';
import VehicleMonitorPanel from './panels/VehicleMonitorPanel.vue';
import EmergencyPanel from './panels/EmergencyPanel.vue';
import EnergyPanel from './panels/EnergyPanel.vue';
import PlanPanel from './panels/PlanPanel.vue';
import { eventBus } from '../../../plugins/eventBus';

// 初始化路由
const router = useRouter();
const route = useRoute();

// 获取注入的 supermapRef
const supermapRef = inject('supermapRef');

// 导航菜单项
const navList = [
  "隧道概况",
  "值守点位置",
  "设备概况",
  "车辆监测",
  "突发事件",
  "能效分析",
  "群控预案",
];

// 地图模式选项
const modeList = ["高精模型", "倾斜模型", "卫星影像", "GIS地图"];

// 组件映射表 - 将导航索引映射到对应的组件
const panelComponents = {
  0: TunnelOverviewPanel,
  1: GuardPointsPanel,
  2: DeviceOverviewPanel,
  3: VehicleMonitorPanel,
  4: EmergencyPanel,
  5: EnergyPanel,
  6: PlanPanel,
};

const options = [{ value: "tunnel1", label: "隧道1" }];
const value = ref("");
const activeNavIndex = ref(-1); // 初始无高亮
const activeModes = ref([false, false, false, true]); // 高精模型、倾斜模型、卫星影像默认为蓝色背景，GIS地图默认为灰色背景
const bottomBtnActiveIndex = ref(0); // 底部按钮初始高亮为隧道摄像机

// 根据当前活动的导航索引计算要显示的组件
const currentPanelComponent = computed(() => {
  return panelComponents[activeNavIndex.value] || null;
});

// 实时时间数据
const currentYear = ref('');
const currentMonth = ref('');
const currentDay = ref('');
const currentWeekday = ref('');
const currentTime = ref('');

// 更新时间的函数
const updateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const weekday = weekdays[now.getDay()];
  currentYear.value = year;
  currentMonth.value = month;
  currentDay.value = day;
  currentWeekday.value = weekday;
  currentTime.value = `${hours}:${minutes}:${seconds}`;
};

// 组件初始化前就确定是否需要导航
onBeforeMount(() => {
  // 只有首次加载且没有navIndex参数时，才自动跳转到隧道概况页面
  if (route.path === '/' && !route.query.navIndex) {
    router.push('/tunnel-overview');
  }
});

// 在组件挂载时，根据当前路由设置活动导航索引
onMounted(() => {
  updateActiveNavFromRoute();
  // 启动定时器更新时间
  updateTime();
  setInterval(updateTime, 1000);
});

// 监听路由变化，更新导航栏状态
watch(
  () => route.path + JSON.stringify(route.query),
  () => {
    updateActiveNavFromRoute();
  }
);

// 根据当前路由更新导航高亮状态
function updateActiveNavFromRoute() {
  if (route.path === '/tunnel-overview') {
    activeNavIndex.value = 0;
  } else if (route.path === '/guardpost') {
    activeNavIndex.value = 1;
  } else if (route.path === '/' && route.query.navIndex) {
    const navIndex = parseInt(route.query.navIndex);
    if (!isNaN(navIndex) && navIndex >= 0 && navIndex <= 6) {
      activeNavIndex.value = navIndex;
    }
  } else if (route.path === '/') {
    // 如果是首页没有navIndex，默认不高亮任何导航
    activeNavIndex.value = -1;
  }
}

// 点击导航项时的处理函数
function onNavClick(item, index) {
  // 设备概况相关优化
  if (index === 2) { // 设备概况索引
    // 添加加载状态
    document.body.classList.add('loading-nav');
    
    // 通过事件总线发出预加载请求
    eventBus.emit('prepare-device-overview');
    
    // 延迟路由跳转，给预加载一些时间
    setTimeout(() => {
      activeNavIndex.value = index;
      router.push({
        path: '/',
        query: { navIndex: index }
      }).catch(err => {
        console.error(`导航到主页(navIndex=${index})出错:`, err);
      }).finally(() => {
        // 移除加载状态
        document.body.classList.remove('loading-nav');
      });
    }, 100);
    
    return;
  }
  
  // 如果当前已经是这个导航项，则尝试重新加载页面内容而不是直接返回
  if (activeNavIndex.value === index) {
    try {
      if (index === 0) {
        // 如果已经在隧道概况页面，尝试重新初始化地图
        if (window.initMap) {
          window.initMap();
        } else {
          // 如果没有直接访问地图初始化函数，则通过重新加载路由实现
          router.push('/tunnel-overview').catch(console.error);
        }
      } else if (index === 1) {
        // 如果已经在值守点位置页面，尝试重新初始化地图
        if (window.initMap) {
          window.initMap();
        } else {
          router.push('/guardpost').catch(console.error);
        }
      }
    } catch (err) {
      console.error("重新加载内容失败:", err);
    }
    return;
  }
  
  try {
    // 根据不同的导航项进行不同处理
    if (index === 0) { // 隧道概况
      // 设置活动索引
      activeNavIndex.value = index;
      // 路由跳转到隧道概况页面
      router.push('/tunnel-overview').catch(err => {
        console.error('导航到隧道概况出错:', err);
      });
    } else if (index === 1) { // 值守点位置
      // 设置活动索引
      activeNavIndex.value = index;
      router.push('/guardpost').catch(err => {
        console.error('导航到值守点位置出错:', err);
      });
    } else {
      // 其他导航项，确保先清除任何现有路由
      // 然后跳转到主页面(三维地图)，并传递导航索引
      
      // 先设置当前活动索引，以便立即更新导航栏状态
      activeNavIndex.value = index;
      
      if (route.path !== '/') {
        // 如果不在主页，先跳转到主页
        router.push({
          path: '/',
          query: { navIndex: index }
        }).catch(err => {
          console.error(`导航到主页(navIndex=${index})出错:`, err);
        });
      } else {
        // 已经在主页，只更新查询参数
        router.push({
          path: '/',
          query: { navIndex: index }
        }).catch(err => {
          console.error(`导航到主页(navIndex=${index})出错:`, err);
        });
      }
    }
  } catch (error) {
    console.error(`导航到 ${item} 时出错:`, error);
  }
}

// 点击模式切换按钮时的处理函数
function onModeClick(mode, index) {
  // 切换按钮状态
  activeModes.value[index] = !activeModes.value[index];
  
  // 使用事件总线触发事件
  if (index === 0) { // 高精模型按钮
    eventBus.emit('toggle-high-precision');
    console.log('触发高精模型控制事件');
  } 
  else if (index === 1) { // 倾斜模型按钮
    eventBus.emit('toggle-oblique');
    console.log('触发倾斜模型控制事件');
  }
}

// 点击底部按钮时的处理函数
function onBottomBtnClick(index) {
  bottomBtnActiveIndex.value =
    index === bottomBtnActiveIndex.value ? -1 : index;
}
</script>

<style lang="scss" scoped>
.top-container {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 100;
}

.top-header {
  width: 100%;
  height: 67.4px;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  pointer-events: auto;
  background-image: url('@/assets/image/TunnelOverviewPanel/源.png');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  padding: 0 32px;

  .time-display {
    position: absolute;
    left: 32px;
    top:45%;
    transform: translateY(-50%);
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 2px;
    color: #fff;
    font-family: 'Source Han Sans CN', 'Microsoft YaHei', sans-serif;
    .date-number {
      font-family: DIN Alternate;
      font-size: 14px;
      color: #fff;
      opacity: 1;
    }
    .date-text {
      font-family: 'Source Han Sans CN', 'Microsoft YaHei', sans-serif;
      font-weight: 400;
      font-size: 14px;
      color: #fff;
      opacity: 0.6;
      margin-right: 2px;
    }
    .weekday {
      font-family: 'Source Han Sans CN', 'Microsoft YaHei', sans-serif;
      font-weight: 400;
      font-size: 14px;
      color: #fff;
      opacity: 0.6;
      margin: 0 8px 0 8px;
    }
    .time {
      font-family: 'DIN Alternate', 'Arial', sans-serif;
      // font-weight: bold;
      font-size: 14px;
      color: #fff;
      letter-spacing: 1px;
      opacity: 1;
    }
  }

  p {
    position: absolute;
    left: 50%;
    top: 40%;
    transform: translate(-50%, -50%);
    width: 360px;
    height: 35px;
    margin: 0;
    font-family: FZCuYuan-M03S;
    font-weight: 600;
    font-size: 36px;
    line-height: 35px;
    text-align: center;
    color: #fff;
    background: linear-gradient(0deg, #e2e2e2 0.4%, #fefbf9 27.4%, #fff 71.5%, #7cbaff 100%);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    z-index: 1;
  }

  .header-right {
    width: 60px; // 预留宽度用于平衡布局
    height: 1px;
  }
}

.search-bar {
  position: absolute;
  top: 67.4px;
  left: 23px;
  display: flex;
  gap: 10px;
  height: 48px;
  align-items: center;
  pointer-events: auto;
  z-index: 1001;
}

.search-input-container {
  position: relative;
  height: 36px;
}

.search-input {
  height: 36px;
  width: 180px;
  background: rgba(5, 34, 73, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  color: white;
  padding: 0 30px 0 10px;
  font-size: 14px;
  outline: none;
}

.search-input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.search-icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: white;
  font-size: 16px;
}

// 导航栏
.nav-bar {
  background-image: url('@/assets/image/TunnelOverviewPanel/组 8080.png');
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 0;
  width: 1449px;
  height: 86px;
  display: flex;
  justify-content: center;
  align-items: flex-end;
  pointer-events: auto;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  gap: 2px;
  padding-bottom: 8px;
}

.nav-item {
  position: relative;
  width: 101px;
  height: 43px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  /* margin: 0 8px;  // 移除原有margin，避免和gap冲突 */
  background-image: url('@/assets/image/TunnelOverviewPanel/矩形 505 拷贝 3.png');
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;

  &.active {
    background-image: url('@/assets/image/TunnelOverviewPanel/矩形 505.png');
  }

  .icon-indicator {
    position: absolute;
    top: -10px;
    left: 50%;
    transform: translateX(-50%);
    width: 21px;
    height: 16px;
    background-image: url('@/assets/image/TunnelOverviewPanel/组 40.png');
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
  }

  .nav-text {
    width: 80px;
    height: 16px;
    font-family: Source Han Sans CN;
    font-size: 16px;
    color: #FFFFFF;
    text-align: center;
    line-height: 16px;
  }
}

// 左下角模式切换按钮
.mode-buttons {
  position: absolute;
  left: 20px;
  bottom: 100px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  pointer-events: auto;
}

.mode-button {
  width: 100px;
  height: 36px;
  color: #fff;
  border: none;
  border-radius: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  background: url('@/assets/image/TunnelOverviewPanel/矩形 2660 拷贝 2.png') no-repeat center/cover;
  transition: all 0.3s;

  &.active {
    background: url('@/assets/image/TunnelOverviewPanel/矩形 2660 拷贝 3.png') no-repeat center/cover;
    color: #fff;
  }
}

// 底部中间控制按钮
.bottom-buttons {
  position: absolute;
  right: 20px;
  bottom: 33px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  pointer-events: auto;
}

.bottom-btn-bg {
  width: 160px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('@/assets/image/TunnelOverviewPanel/组 8081.png') no-repeat center/cover;
  transition: background-image 0.2s;
}

.bottom-btn-bg.active {
  background: url('@/assets/image/TunnelOverviewPanel/组 98.png') no-repeat center/cover;
}

.bottom-btn {
  background: transparent;
  color: #fff;
  border: none;
  border-radius: 0;
  padding: 0 24px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  height: 56px;
  width: 100%;
  justify-content: center;
  transition: color 0.2s;
}

.bottom-btn.active {
  color: #00ffff;
}

// 右下角缩放控制按钮
.zoom-controls {
  position: absolute;
  right: 192px;
  bottom: 29px;
  display: flex;
  flex-direction: row;
  gap: 2px;
  pointer-events: auto;
}

.zoom-btn {
  width: 48px;
  height: 48px;
  border: none;
  border-radius: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: transparent;
  padding: 0;
}

// 右侧内容面板
.right-panel {
  position: absolute;
  top: 80px;
  right: 2vw;
  width: 40vw;
  min-width: 340px;
  max-width: 700px;
  pointer-events: auto;
  z-index: 900;
}
</style>
